package websocket

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	utils "duoke/utils/common"
	"duoke/utils/gjwt"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/mitchellh/mapstructure"
)

// LoginController 用户登录
func LoginController(client *Client, req *Request) {
	token := gconv.String(req.Data["token"])
	userId := 0
	if token == "" {
		client.SendMsg(&WResponse{
			Event: Login,
			Data:  "login fail 1",
		})
		return
	} else {
		result, err := gjwt.Parse(token)
		if err != nil {
			client.SendMsg(&WResponse{
				Event: Login,
				Data:  err.Error(),
			})
			return
		}
		if result.Uid == 0 {
			client.SendMsg(&WResponse{
				Event: Login,
				Data:  "请重新登录",
			})
			return
		}
		userId = result.Uid
	}
	if userId == 0 {
		client.SendMsg(&WResponse{
			Event: Login,
			Data:  "login fail 2",
		})
		return
	}
	// 用户登录
	login := &login{
		UserId: gconv.Uint64(userId),
		Client: client,
	}
	clientManager.Login <- login
	client.SendMsg(&WResponse{
		Event: Login,
		Data:  "success",
	})
}

func IsAppController(client *Client) {
	client.isApp = true
}

// JoinController 加入
func JoinController(client *Client, req *Request) {
	name := gconv.String(req.Data["name"])
	if !client.tags.Contains(name) {
		client.tags.Append(name)
	}
	client.SendMsg(&WResponse{
		Event: Join,
		Data:  client.tags.Slice(),
	})
}

// QuitController 退出
func QuitController(client *Client, req *Request) {
	name := gconv.String(req.Data["name"])
	if client.tags.Contains(name) {
		client.tags.RemoveValue(name)
	}
	client.SendMsg(&WResponse{
		Event: Quit,
		Data:  client.tags.Slice(),
	})
}
func PingController(client *Client) {
	currentTime := uint64(gtime.Now().Unix())
	client.Heartbeat(currentTime)
}
func VideoController(client *Client, req *Request) {
	data := gconv.String(req.Data["data"])
	key := []byte("Q!fqhthlsFuazZ(gvlWTY(h(n_x*2i4+")
	iv := []byte("Js8K1kDYC^K^FuWZ")
	encrypt, err := utils.Common.AESDecrypt(data, key, iv)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: Video,
			Data:  "error",
		})
	}
	var m model.VideoDuration
	err = json.Unmarshal([]byte(encrypt), &m)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: Video,
			Data:  err.Error(),
		})
		return
	}
	result, err := gjwt.Parse(m.Token)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: Login,
			Data:  err.Error(),
		})
		return
	}
	progress := (m.Duration / m.TotalDuration) * 100
	str := fmt.Sprintf("%.2f", progress)
	courseProgress := tables.CourseProgress{
		FromId:           m.VideoId,
		LearningProgress: gconv.Float32(str),
		UserId:           result.Uid,
		WatchTime:        float32(m.Duration),
	}
	err = service.CourseProgress.Save(&courseProgress)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: Video,
			Data:  err.Error(),
		})
		return
	}
	client.SendMsg(&WResponse{
		Event: Video,
		Data:  "success",
	})
}
func ShortVideoController(client *Client, req *Request) {
	var c gin.Context
	resp, err := Gjwt(req, &c)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: ShortVideo,
			Data:  err.Error(),
		})
		return
	}
	var statistics model.ShortVideWs
	err = mapstructure.Decode(resp.Data, &statistics)
	// 观看 点赞 收藏
	if err != nil {
		client.SendMsg(&WResponse{
			Event: ShortVideo,
			Data:  err.Error(),
		})
		return
	}
	err = service.ShortWatch.Save(&c, &statistics)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: ShortVideo,
			Data:  err.Error(),
		})
		return
	}
	// 统计
	err = service.Shortvideo.Statistics(&c, &statistics)
	if err != nil {
		client.SendMsg(&WResponse{
			Event: ShortVideo,
			Data:  err.Error(),
		})
		return
	}
	client.SendMsg(&WResponse{
		Event: ShortVideo,
		Data:  "success",
	})
}
